﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Meeting.DBUtility;
using Meeting.Model;
using Newtonsoft.Json;
using System.Data.SqlClient;
using System.Net;
using System.IO;
using System.Configuration;

namespace Meeting.BLL
{

    /// <summary>
    /// 模块作者：吴龙波
    /// 模块日期：2013-02-16
    /// 模块功能：视频会议室vedioRoom 增删查改
    /// </summary>
    public class VideoRoom
    {
        public string errorString = "";
        private string VideoQueryUrl = "http://192.168.10.166/MeetingControl/query";
        //private string VideoQueryUrl = "https://as.iomeeting.cn/MeetingControl/query";
        //获取会议室表数据
        private DataSet GetVideoRooms(string filter)
        {
            string sql = "Select  * VideoRoom Where 1=1 ";
            if (!string.IsNullOrEmpty(filter)) sql += " And " + filter;
            try
            {
                return DbHelperSQL.Query(sql);
            }
            catch (Exception ex)
            {
                errorString = ex.Message;
                return null;
            }
        }
        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public string GetPage(int pageIndex, int pageSize, string filter)
        {
            int nAllRecord = 0, nAllPages = 0;

            DataTable dt = DbHelperSQL.GetPage(" cast(Id as varchar(50))  ", "  *  ", " dbo.VideoRoom   ", filter, " Number ", pageIndex, pageSize, out nAllRecord, out nAllPages);
            if (dt == null) return "";
            JsonGrid jr = new JsonGrid();
            jr.total = nAllRecord;
            jr.rows = dt;
            return JsonConvert.SerializeObject(jr);
        }
        /// <summary>
        /// 编号不重复
        /// </summary>
        public bool Exists(string number)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from VideoRoom");
            strSql.Append(" where Number=@Number ");
            SqlParameter[] parameters = {
					new SqlParameter("@Number", SqlDbType.NVarChar,128)};
            parameters[0].Value = number;

            return DbHelperSQL.Exists(strSql.ToString(), parameters);
        }
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public bool Add(Meeting.Model.VideoRoom model)
        {
            if (Exists(model.Number))
            {
                errorString = "已存在该编号";
                return false;
            }
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into VideoRoom(");
            strSql.Append("Id,Number,Name,HostEmail,HostPass,IsTemp)");
            strSql.Append(" values (");
            strSql.Append("@Id,@Number,@Name,@HostEmail,@HostPass,@IsTemp)");
            SqlParameter[] parameters = {
					new SqlParameter("@Id", SqlDbType.UniqueIdentifier,16),
					new SqlParameter("@Number", SqlDbType.NVarChar,128),
					new SqlParameter("@Name", SqlDbType.NVarChar,128),
					new SqlParameter("@HostEmail", SqlDbType.NVarChar,128),                   
					new SqlParameter("@HostPass", SqlDbType.NVarChar,128),
                    new SqlParameter("@IsTemp", SqlDbType.Bit,1)};
            parameters[0].Value = Guid.NewGuid();
            parameters[1].Value = model.Number;
            parameters[2].Value = model.Name;
            parameters[3].Value = model.HostEmail;
            parameters[4].Value = model.HostPass;
            parameters[5].Value = model.IsTemp;


            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private string GetOldNumber(Guid id)
        {
            string sql = "Select Number From VideoRoom Where Id = '" + id + "' ";
            DataSet ds = DbHelperSQL.Query(sql);
            if (ds == null || ds.Tables[0].Rows.Count < 1) return "";
            return ds.Tables[0].Rows[0]["Number"].ToString();
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Meeting.Model.VideoRoom model)
        {
            string oldNumber = GetOldNumber(model.Id);
            if (oldNumber == "")
            {
                errorString = "获取原始编号出错";
                return false;
            }
            //
            if (oldNumber != model.Number)
            {
                if (Exists(model.Number))
                {
                    errorString = "已存在该编号，请修改编号";
                    return false;
                }
            }
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update VideoRoom set ");
            strSql.Append("Number=@Number,");
            strSql.Append("Name=@Name,");
            strSql.Append("HostEmail=@HostEmail,");
            strSql.Append("HostPass=@HostPass,");
            strSql.Append("IsTemp=@IsTemp");
            strSql.Append(" where Id=@Id ");
            SqlParameter[] parameters = {
					new SqlParameter("@Number", SqlDbType.NVarChar,128),
					new SqlParameter("@Name", SqlDbType.NVarChar,128),
					new SqlParameter("@HostEmail", SqlDbType.NVarChar,128),
					new SqlParameter("@HostPass", SqlDbType.NVarChar,128),
                    new SqlParameter("@IsTemp", SqlDbType.Bit,1),
					new SqlParameter("@Id", SqlDbType.UniqueIdentifier,16)};
            parameters[0].Value = model.Number;
            parameters[1].Value = model.Name;
            parameters[2].Value = model.HostEmail;
            parameters[3].Value = model.HostPass;
            parameters[4].Value = model.IsTemp;
            parameters[5].Value = model.Id;

            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(Guid Id)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from VideoRoom ");
            strSql.Append(" where Id=@Id ");
            SqlParameter[] parameters = {
					new SqlParameter("@Id", SqlDbType.UniqueIdentifier,16)};
            parameters[0].Value = Id;

            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 批量删除数据
        /// </summary>
        public bool DeleteList(string ids)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from VideoRoom ");
            strSql.Append(" where Id in (" + ids + ")  ");
            int rows = DbHelperSQL.ExecuteSql(strSql.ToString());
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 检测视频会议室是否可以使用
        /// </summary>
        /// <param name="hostEmail"></param>
        /// <param name="hostPass"></param>
        /// <returns></returns>
        public bool CheckVideoRoomUsability(string hostEmail, string hostPass)
        {
            //string url = ConfigurationManager.AppSettings["VideoQueryUrl"] + "?hostEmail=" + hostEmail + "&hostPassword=" + hostPass;
            string url = VideoQueryUrl + "?hostEmail=" + hostEmail + "&hostPassword=" + hostPass;
            try
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var responseText = streamReader.ReadToEnd();
                    string[] results = responseText.Split(',');
                    if (results[0] == "0")
                    {
                        return true;
                    }
                    else
                        return false;
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 获取视频会议室状态
        /// </summary>
        /// <param name="hostEmail"></param>
        /// <param name="hostPass"></param>
        /// <returns></returns>
        public string GetVideoRoomStatus(string hostEmail, string hostPass)
        {
            //string url = ConfigurationManager.AppSettings["VideoQueryUrl"] + "?hostEmail=" + hostEmail + "&hostPassword=" + hostPass;
            string url = VideoQueryUrl + "?hostEmail=" + hostEmail + "&hostPassword=" + hostPass;
            try
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    return streamReader.ReadToEnd();
                }
            }
            catch
            {
                return "";
            }
        }
    }
}
